package com.pocketsweet.ui.uilib.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.GetCallback;
import com.easemob.EMCallBack;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.VoiceCallActivity;
import com.pocketsweet.model.MLCustomizationRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * 
 * @author Kam
 * 
 */
public class NewLoverInvitedAdapter extends
		BaseListAdapter<MLCustomizationRecord> {
	private Context context;

	public NewLoverInvitedAdapter(Context ctx) {
		super(ctx);
		this.context = ctx;
	}

	public NewLoverInvitedAdapter(Context ctx, List<MLCustomizationRecord> datas) {
		super(ctx, datas);
		this.context = ctx;
	}

	@Override
	public int getCount() {
		return datas.size();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_new_invited, parent,
					false);
			viewHolder = new ViewHolder(convertView);
			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();

		}
		viewHolder.refreshView(datas.get(position), position);
		return convertView;
	}

	public class ViewHolder implements View.OnClickListener {
		ImageView imgAvatar;
		TextView tvuserName;
		TextView tvUserAge;
		TextView tvFrom;
		TextView tvType;
		TextView tvStar;
		ImageView tvWilling;
		TextView tvTime;
		MLCustomizationRecord item;
		MLUser mlUser;
		public View parent;

		public ViewHolder(View parent) {
			this.parent = parent;
			initView(parent);
		}

		public void initView(View parent) {
			imgAvatar = (ImageView) parent.findViewById(R.id.imgAvatar);
			tvuserName = (TextView) parent.findViewById(R.id.tvuserName);
			tvUserAge = (TextView) parent.findViewById(R.id.tvUserAge);
			tvFrom = (TextView) parent.findViewById(R.id.tvFrom);
			tvStar = (TextView) parent.findViewById(R.id.tvStar);
			tvWilling = (ImageView) parent.findViewById(R.id.tvWilling);
			tvTime = (TextView) parent.findViewById(R.id.tvTime);
			tvType = (TextView) parent.findViewById(R.id.tvType);
			// tvNoRemark = (TextView) parent.findViewById(R.id.tvNoRemark);
		}

		public void refreshView(MLCustomizationRecord item, int i) {
			this.item = item;
			// 设置图片
			mlUser = item.getSponsor();
			String avatar = mlUser.getAvatarUrl();
			if (avatar != null && !avatar.equals("")) {
				UserService.displaySquare(avatar, imgAvatar);
			} else {
				imgAvatar.setImageResource(R.drawable.img_avatar_girl);
			}
			if (!StringUtils.isEmpty((mlUser.getNickname()))) {
				tvuserName.setText(mlUser.getNickname());
			}
			if (!StringUtils.isEmpty((mlUser.getBelong()))) {
				tvType.setText(mlUser.getBelong());
			}
			// 设置年龄
			if (!StringUtils.isEmpty(String.valueOf(mlUser.getAgeNum()))) {
				tvUserAge.setText(String.valueOf(mlUser.getAgeNum()));
			}
			// 设置性别颜色
			if (mlUser.getGender() == 1) {
				tvUserAge
						.setBackgroundResource(R.drawable.shape_rectangle_bule);
			} else if (mlUser.getGender() == 2) {
				// 设置颜色
				tvUserAge.setBackgroundResource(R.drawable.shape_rectangle_red);
			}
			// 设置星座
			tvStar.setText(mlUser.getConstellation());
			// 设置地理位置
			String location = mlUser.getLocationCity();
			if (StringUtils.isEmpty(location)) {
				location = mlUser.getLocationProvince();
			}
			tvFrom.setText(location);
			if (item.getCreatedAt() != null) {
//				tvTime.setText(ToolKits.millisecs2DateString(mlUser
//						.getCreatedAt().getTime()));
				tvTime.setText(ToolKits.getTimeDiff(item.getCreatedAt()));
			}
			tvWilling.setOnClickListener(this);
			// parent.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			if (v.equals(tvWilling)) {
				AVAnalytics.onEvent(ctx, "情感热线（打电话）");

				AVQuery<MLCustomizationRecord> record = new AVQuery<MLCustomizationRecord>(
						"MLCustomizationRecord");
				record.getInBackground(item.getObjectId(),
						new GetCallback<MLCustomizationRecord>() {

							@Override
							public void done(
									MLCustomizationRecord mlCustomizationRecord,
									AVException arg1) {
								Main.record=mlCustomizationRecord;
								if (mlCustomizationRecord == null) {
									final MyAlertDialog dialogCache = new MyAlertDialog(
											context)
											.builder()
											.setMsg("对方已经取消邀请啦")
											.setTitle("提示")
											.setPositiveButton("确定",
													new OnClickListener() {
														@Override
														public void onClick(
																View v) {
														}
													});
									dialogCache.show();

								} else if (mlCustomizationRecord.getStatus() == C.LOVE_CALL_FINISH) {
									final MyAlertDialog dialogCache = new MyAlertDialog(
											context)
											.builder()
											.setMsg("已经有口袋恋人打过电话了")
											.setTitle("提示")
											.setPositiveButton("确定",
													new OnClickListener() {
														@Override
														public void onClick(
																View v) {
														}
													});
									dialogCache.show();
								} else if (mlCustomizationRecord.getStatus() == C.LOVE_CALL_WAITING) {
									// 发送恋爱呼叫透传
//									mlCustomizationRecord.setWinner(UserService.getCurrentUser());
//									mlCustomizationRecord.saveInBackground();
									EMMessage cmdMsg = EMMessage
											.createSendMessage(EMMessage.Type.CMD);
									String action = C.ACTION_CUSTOMAZITION_CALL;// action可以自定义，在广播接收时可以收到
									CmdMessageBody cmdBody = new CmdMessageBody(
											action);
									cmdMsg.setReceipt(mlUser.getObjectId());
									cmdMsg.setAttribute("from",
											UserService.getCurrentUserId());
									cmdMsg.addBody(cmdBody);
									EMChatManager.getInstance().sendMessage(
											cmdMsg, new EMCallBack() {

												@Override
												public void onSuccess() {
													context.startActivity(new Intent(
															context,
															VoiceCallActivity.class)
															.putExtra(
																	"username",
																	mlUser.getObjectId())
															.putExtra(
																	"nickname",
																	mlUser.getNickname())
															.putExtra(
																	"isComingCall",
																	false)
															.putExtra(
																	"avatar",
																	mlUser.getAvatarUrl())
															.putExtra(
																	"isCustomazition",
																	true)
															.addFlags(
																	Intent.FLAG_ACTIVITY_NEW_TASK));
												}

												@Override
												public void onError(int arg0,
														String arg1) {

												}

												@Override
												public void onProgress(
														int arg0, String arg1) {

												}
											});
								}
							}
						});

			}
		}
	}

}
